//index.js
//获取应用实例
const app = getApp()
var t = require('./../../utils/request.js');
var timer1 = '';


// 时间戳转时分秒
function getTimeFormat(timestamp) {
  // var timestamp = 416090986
  var day = parseInt(timestamp / 1000 / 3600 / 24)
  var hous = parseInt((timestamp) / 1000 / 3600)
  var min = parseInt((timestamp - hous * 1000 * 3600) / 1000 / 60)
  var second = parseInt(timestamp / 1000) % 60
  var second2 = parseInt(timestamp % 1000 / 100)
  return [addZero(day), addZero(hous), addZero(min), addZero(second), second2]
}

function addZero(num) {
  if (num < 10) {
    return '0' + num;
  } else {
    return num.toString();
  }
}

Page({
  data: {
    userInfo: {},  // 用户信息
    show: false,   // 中奖弹框
    isTicket: false,  // 是否中奖
    activeTime: ['00','00','00','00','00'], // 倒计时
    mask_view: false,
    activeStatus: 0,

    imgUrls: [
      'http://qny.zhiniugroup.com/blog/20190107143235.png',
      'http://qny.zhiniugroup.com/blog/20190107143212.png',
    ],
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 1000
  },
  //事件处理函数
  bindViewTap: function() {ticketNum
    wx.navigateTo({
      url: '../logs/logs'
    })
  },

  countdown: function (time) {
    var that = this
    var timestamp = time
    timer1 = setInterval(function () {
      that.setData({
        activeTime: getTimeFormat(timestamp)
      })
      timestamp = timestamp - 1000
    }, 1000)
  },

  toMyLocation: function () {
    wx.getSetting({
      success: (res) => {
        console.log(res); console.log(res.authSetting['scope.userLocation']);
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          console.log(99999)
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
            showCancel: true,
            cancelText: '取消',
            cancelColor: '#000000',
            confirmText: '确认',
            confirmColor: '#3CC51F',
            success: function (res) {
              if (res.confirm) {
                wx.openSetting({
                  success: function (data) {
                    console.log(data); if (data.authSetting["scope.userLocation"] == true) {
                      wx.showToast({ title: '授权成功', icon: 'success', duration: 5000 })
                    }
                  }
                })
              }
            }
          })
        } else {
          console.log('获取用户经纬度')
          wx.getLocation({
            type: 'wgs84',
            success(res) {
              const latitude = res.latitude
              const longitude = res.longitude
              console.log(res)
              t.toPost('/minip/user/location', {
                lat: latitude,
                lng: longitude
              }, (res)=> {
                console.log(res)
                // if (res.data.result.address.indexOf('市') != -1 && res.data.result.address.indexOf('区') != -1) {
                //   wx.setStorageSync('address', res.data.result.address.split('市')[1].split('区')[0])
                //   wx.navigateTo({
                //     url: '/pages/nearby/nearby'
                //   })
                // } else {
                //   wx.showToast({
                //     title: '请选择具体地址',
                //   })
                // }
                
                if (res) {
                  if (res.data.result.address_component.city.indexOf('市') != -1){
                    wx.setStorageSync('address', res.data.result.address_component.city.split('市')[0])
                  }
                  wx.navigateTo({
                    url: '/pages/nearby/nearby'
                  })
                } else {
                  wx.showToast({
                    title: '请选择具体地址',
                  })
                }
              })

            }
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      show: false
    })

    t.toPost('/minip/active/config', {
    }, (res) => {
      console.log(res)
      if (res. code === '000000') {
        this.setData({
          activeStatus: 0,
          ticketNum: res.data.ticket_num.toString()
        })
        this.countdown(res.data.times * 1000)
      }
      if (res.code === '700001') {
        this.setData({
          activeStatus: 1
        })
      }

      if (res.code === '700002') {
        this.setData({
          activeStatus: 2
        })
      }
    })


    if (wx.getStorageSync('userInfo')) {
      t.toPost('/minip/user/info', {
        uid: wx.getStorageSync('userInfo').id
      }, (res) => {
        this.setData({
          userInfo: res.data
        })
      })
    } else {
      this.setData({
        mask_view: true
      })
    }
  },

  onLoad: function () {
    
  },

  // 跳转附近门店页面
  toNearby: function () {
    this.toMyLocation()
    // wx.chooseLocation({
    //   success: function(res) {
    //     console.log(res, 233)
    //     console.log(res.address.indexOf('市'), 99)
    //     if (res.address.indexOf('市') != -1 && res.address.indexOf('区') != -1) {
    //       console.log(res.address.split('市')[1].split('区')[0])
    //       wx.setStorageSync('address', res.address.split('市')[1].split('区')[0])
    //       wx.navigateTo({
    //         url: '/pages/nearby/nearby'
    //       })
    //     } else {
    //       wx.showToast({
    //         title: '请选择具体地址',
    //       })
    //     }
        
    //   }
    // })

  },

  toC: function () {
    wx.navigateTo({
      url: '/pages/chou2/index',
    })
  },


  // 跳转奖品和礼券页面
  toPrize: function () {

    wx.navigateTo({
      url: '/pages/prize/prize'
    })
  },

  // 跳转到信息填写页面，并完成支付
  toInfo: function () {
    wx.navigateTo({
      url: '/pages/info/info'
    })
  },

  // 点击A5产品页面
  toWebView: function (event) {
    var type = event.currentTarget.dataset.type
    wx.navigateTo({
      url: '/pages/webview/webview?type=' + type
    })
  },
  
  // 抽奖的业务逻辑
  choujiang: function () {

    // 如果用户信息存在那么就执行操作
    if (wx.getStorageSync('userInfo')) {
      t.toPost('/minip/user/info', {
        uid: wx.getStorageSync('userInfo').id
      }, (res) => {
        console.log(res)
        if (res.code == '000000') {
          if (res.data.is_ticket == 0) {
            wx.navigateTo({
              url: '/pages/chou2/index',
            })
          } else {
            wx.navigateTo({
              url: '/pages/chou1/index',
            })
          }
        }
      })
    } else {
      this.onShow()
    }
    
  },

  // 获取用户信息
  getUserInfo: function (e) {
    var that = this

    // 播放音效
    const innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.autoplay = true
    innerAudioContext.src = 'https://market.jackgroup.cn/zhong.mp3'
    innerAudioContext.onPlay(() => {
    })

    wx.showLoading({
      title: '登录中',
    })

    // 登录
    wx.login({
      success: function (res) {
        new Promise(resolve => {
          wx.getUserInfo({
            success: function (res) {
              console.log(res, '==============userinfo==============')
              if (res.errMsg === 'getUserInfo:ok') {
                wx.setStorageSync('encryptedData', res.encryptedData)
                wx.setStorageSync('iv', res.iv)
                resolve();
              } else {
              }
            }
          })
        })
          .then(function () {
            var param = {
              code: res.code,
              enc: wx.getStorageSync('encryptedData'),
              iv: wx.getStorageSync('iv')
            }
            if (that.data.activeStatus == 1) {
              wx.hideLoading()

              wx.showToast({
                icon: 'none',
                title: '活动尚未开始',
              })
              return;
            }

            if (that.data.activeStatus == 2) {
              wx.hideLoading()

              wx.showToast({
                icon: 'none',
                title: '活动已结束',
              })
              return;
            }

            t.toPost('/minip/user/login', param, (res) => {
              if (res.code === '000000') {
                wx.hideLoading()
                wx.setStorageSync('userInfo', res.data)

                t.toPost('/minip/user/isticket', {
                  uid: res.data.id
                }, (res) => {
                  console.log(res)
                  if (res.code === '000000') {
                    // todo 修改1: 有券就跳转完善用户信息
                    wx.navigateTo({
                      url: '/pages/info/info'
                    })
                  }

                  if (res.code === '900001') {
                    that.setData({
                      isTicket: false
                    })
                    that.setData({
                      show: true
                    })
                  }

                  if (res.code === '900002') {
                    wx.showToast({
                      title: res.message,
                    })
                  }

                  if (res.code === '400001') {
                    wx.showToast({
                      title: '您已经抢过抵购券了！！',
                    })
                  }
                })
                
              } else {
                wx.showToast({
                  title: '用户信息获取失败',
                })
              }

            }, (err) => {
              console.log(err)
            })
          })
      }
    })
  },

  getUserInfo2: function() {
    var that = this

    // 播放音效
    // const innerAudioContext = wx.createInnerAudioContext()
    // innerAudioContext.autoplay = true
    // innerAudioContext.src = 'https://market.jackgroup.cn/jb.mp3'
    // innerAudioContext.onPlay(() => {
    // })

    wx.showLoading({
      title: '用户信息获取中...',
    })

    // 登录
    wx.login({
      success: function (res) {
        new Promise(resolve => {
          wx.getUserInfo({
            success: function (res) {
              console.log(res, '==============userinfo==============')
              if (res.errMsg === 'getUserInfo:ok') {
                wx.setStorageSync('encryptedData', res.encryptedData)
                wx.setStorageSync('iv', res.iv)
                resolve();
              } else {
              }
            }
          })
        })
          .then(function () {
            var param = {
              code: res.code,
              enc: wx.getStorageSync('encryptedData'),
              iv: wx.getStorageSync('iv')
            }
            t.toPost('/minip/user/login', param, (res) => {
              if (res.code === '000000') {
                wx.hideLoading()
                wx.setStorageSync('userInfo', res.data)
                that.setData({
                  mask_view: false
                })
              } else {
                wx.showToast({
                  title: '用户信息获取失败',
                })
              }

            }, (err) => {
              console.log(err)
            })
          })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(timer1)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(timer1)
  },

  onClose: function () {
    this.setData({
      show: false
    })
  },

  /**
    * 用户点击右上角分享
  */
  onShareAppMessage: function () {
    return {
      title: '不用剪线头的杰克A5，邀您9.9元抢500体验券！',
      path: '/pages/index/index',
      imageUrl: 'http://qny.zhiniugroup.com/blog/20190106162150.png',
      success: function (res) {
        console.log(res, '分享成功')
      }
    }
  }
})
